//
//  AlertViewController.swift
//  AlertView
//
//  Created by Qiuxk
//  on 2016/11/4.
//  Copyright © 2016年 scale. All rights reserved.
//
//

import UIKit
 
// Animation Styles
public enum KSAnimationStyle {
    case noAnimation, topToBottom, bottomToTop, leftToRight, rightToLeft
}

public struct regionBtnProperty {
    var  text0:UITextField?
    var  text1:UITextField?
    var  btns = [UIButton]()
}

// Action Types
public enum KSActionType {
    case none, selector, closure
}

open class KSButton: UIButton {
    
    var actionType = KSActionType.none
    var target: AnyObject!
    var selector: Selector!
    var action: (() -> Void)!
    var customBackgroundColor: UIColor?
    var customTextColor: UIColor?
    var initialTitle: String!
    var showDurationStatus: Bool = false
    
    public init() {
        super.init(frame: CGRect.zero)
    }
    
    required public init?(coder aDecoder: NSCoder) {
        super.init(coder:aDecoder)
    }
    
    override public init(frame: CGRect) {
        super.init(frame:frame)
    }
}

open class KSAlertView: UIViewController {
    
    public struct LPAppearance {
        
        let kDefaultShadowOpacity: CGFloat
        let kTitleTop: CGFloat
        let kTitleHeight: CGFloat
        let kWindowWidth: CGFloat
        var kWindowHeight: CGFloat
        let kTextFieldHeight: CGFloat
        let kTextViewdHeight: CGFloat
        let kLabelWidth: CGFloat
        let reg_width: CGFloat
        let reg_padding: CGFloat
        let kHorizontalSpacing: CGFloat
        let kVerticalSpacing: CGFloat
        let kTextAlignment: NSTextAlignment
        let kButtonHeight: CGFloat
        let kRegionBtnsHeight: CGFloat
        let contentViewColor: UIColor
        let contentViewBorderColor: UIColor
        let titleColor: UIColor
        let labelColor: UIColor
        
        // Fonts
        let kTitleFont: UIFont
        let kTextFont: UIFont
        let kLalelFont: UIFont
        let kButtonFont: UIFont
        
        // UI Options
        var showCloseButton: Bool
        var showCircularIcon: Bool
        var shouldAutoDismiss: Bool // Set this false to 'Disable' Auto hideView when SCLButton is tapped
        var contentViewCornerRadius: CGFloat
        var fieldCornerRadius: CGFloat
        var buttonCornerRadius: CGFloat
        
        // Actions
        var hideWhenBackgroundViewIsTapped: Bool
        
        init(kDefaultShadowOpacity: CGFloat = 0.7,
             kTitleTop: CGFloat = 10.0,
             kTitleHeight: CGFloat = 25.0,
             kWindowWidth: CGFloat = UIScreen.main.bounds.width - 6,
             kWindowHeight: CGFloat = 178.0,
             kTextFieldHeight: CGFloat = 45.0,
             kTableHeight: CGFloat = 200.0,
             kTextViewdHeight: CGFloat = 120.0,
             kLabelWidth: CGFloat = 70.0,
             reg_padding: CGFloat = 15.0,
             reg_width: CGFloat = ((UIScreen.main.bounds.width - 24 - 24) - 15 * 3) / 4, //  15 是reg_padding的值
             kHorizontalSpacing: CGFloat = 15.0,
             kVerticalSpacing: CGFloat = 14.0,
             kButtonHeight: CGFloat = 45.0,
             kRegionBtnsHeight: CGFloat = 100.0,
             kTitleFont: UIFont = UIFont.systemFont(ofSize: 20),
             kTextFont: UIFont = UIFont.systemFont(ofSize: 14),
             kLalelFont: UIFont = UIFont.systemFont(ofSize: 15),
             kButtonFont: UIFont = UIFont.boldSystemFont(ofSize: 14),
             showCloseButton: Bool = true,
             showCircularIcon: Bool = true,
             shouldAutoDismiss: Bool = true,
             contentViewCornerRadius: CGFloat = 10.0,
             fieldCornerRadius: CGFloat = 3.0,
             buttonCornerRadius: CGFloat = 3.0,
             hideWhenBackgroundViewIsTapped: Bool = false,
             contentViewColor: UIColor = UIColorFromRGB(0xFFFFFF),
             contentViewBorderColor: UIColor = UIColorFromRGB(0xCCCCCC),
             titleColor: UIColor = UIColorFromRGB(0x3b9fc6),
             labelColor: UIColor = UIColorFromRGB(0x4D4D4D),
             kTextAlignment: NSTextAlignment = .center) {
            
            self.kDefaultShadowOpacity = kDefaultShadowOpacity
            self.kTitleTop = kTitleTop
            self.kTitleHeight = kTitleHeight
            self.kWindowWidth = kWindowWidth
            self.kWindowHeight = kWindowHeight
            self.kLabelWidth = kLabelWidth
            self.kTextFieldHeight = kTextFieldHeight
            self.kTextViewdHeight = kTextViewdHeight
            self.kTextAlignment = kTextAlignment
            self.kHorizontalSpacing = kHorizontalSpacing
            self.kVerticalSpacing = kVerticalSpacing
            self.kButtonHeight = kButtonHeight
            self.kRegionBtnsHeight = kRegionBtnsHeight
            
            self.contentViewColor = contentViewColor
            self.contentViewBorderColor = contentViewBorderColor
            self.titleColor = titleColor
            self.labelColor = labelColor
            
            self.kTitleFont = kTitleFont
            self.kTextFont = kTextFont
            self.kLalelFont = kLalelFont
            self.kButtonFont = kButtonFont
            self.reg_width = reg_width
            self.reg_padding = reg_padding
            
            self.showCloseButton = showCloseButton
            self.showCircularIcon = showCircularIcon
            self.shouldAutoDismiss = shouldAutoDismiss
            self.contentViewCornerRadius = contentViewCornerRadius
            self.fieldCornerRadius = fieldCornerRadius
            self.buttonCornerRadius = buttonCornerRadius
            
            self.hideWhenBackgroundViewIsTapped = hideWhenBackgroundViewIsTapped
        }
        
        mutating func setkWindowHeight(_ kWindowHeight: CGFloat) {
            self.kWindowHeight = kWindowHeight
        }
        
    }
    
     var appearance: LPAppearance!
    
    // Members declaration
    var baseView = UIView()
    var contentView = UIView()
    var labelTitle :UILabel = UILabel()
    
    fileprivate var singlePickWithSearchArr = [[String]]() // 单选带搜索，数据集合
    fileprivate var singlePickWithSearchClosure = [((String)->())?]() // 单选带搜索，返回闭包集合
    
   
    fileprivate var inputs = [UITextField]()
    fileprivate var tableS = [UICollectionView]()  /// 单选多选控件集
    
    fileprivate var regionBtns = [UIButton]() /// 选时间时提供多种区间选择
    
    fileprivate var tableHeight = [CGFloat]()
    fileprivate var mutiFlag = [Bool]()
    fileprivate var regionPro:regionBtnProperty?
    var tableDataS = [[SeString]]()
    var colleTitles = [String]()
    fileprivate var subInfoDic: [String : String] = ["":""]
    
    fileprivate var inputWithLabels = [UIView]()
    fileprivate var input = [UITextView]()
    fileprivate var buttons = [KSButton]()
    fileprivate var selfReference: KSAlertView?
    fileprivate var dateTextField: UITextField?
    open var customSubview: UIView?
    
    public init(appearance: LPAppearance) {
        self.appearance = appearance
        super.init(nibName: nil, bundle: nil)
        setup()
    }
    
    required public init() {
        appearance = LPAppearance()
        super.init(nibName: nil, bundle: nil)
        setup()
    }
    
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        appearance = LPAppearance()
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }
    
    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    fileprivate func setup() {
        // set up main view
        view.frame = UIScreen.main.bounds
        view.autoresizingMask = [UIView.AutoresizingMask.flexibleHeight, UIView.AutoresizingMask.flexibleWidth]
        view.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: appearance.kDefaultShadowOpacity)
        view.addSubview(baseView)
        
        baseView.frame = view.frame
        baseView.addSubview(contentView)
        
        contentView.layer.cornerRadius = appearance.contentViewCornerRadius
        contentView.layer.masksToBounds = true
        contentView.layer.borderWidth = 0.5
        contentView.addSubview(labelTitle)
        
        labelTitle.numberOfLines = 1
        labelTitle.textAlignment = .center
        labelTitle.font = appearance.kTitleFont
        labelTitle.frame = CGRect(x: 3, y: appearance.kTitleTop, width: appearance.kWindowWidth - 6, height: appearance.kTitleHeight)
        
        let dividingLine = UIView()
        var dividingLineY = appearance.kTitleTop + appearance.kTitleHeight
        dividingLineY += 4
        dividingLine.backgroundColor = UIColorFromRGB(0x3b9fc6)
        dividingLine.frame = CGRect(x: 3, y: dividingLineY, width: appearance.kWindowWidth - 6, height: 1)
        contentView.addSubview(dividingLine)
        
        let cancelButton:UIButton = UIButton()
        cancelButton.setImage(imageOfCross, for: UIControl.State())
        cancelButton.addTarget(self, action: #selector(hideView), for: .touchUpInside)
        cancelButton.frame = CGRect(x: appearance.kWindowWidth - 20 - 28, y: appearance.kTitleTop, width: 35, height: 30)
        contentView.addSubview(cancelButton)
        
        contentView.backgroundColor = appearance.contentViewColor
        labelTitle.textColor = appearance.titleColor
        contentView.layer.borderColor = appearance.contentViewBorderColor.cgColor
        
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(KSAlertView.tapped(_:)))
        tapGesture.numberOfTapsRequired = 1
        self.view.addGestureRecognizer(tapGesture)
    }
    
    func configUIlayout() {
        let rv = UIApplication.shared.keyWindow! as UIWindow
        let sz = rv.frame.size
        
        view.frame.size = sz
        
        var consumedHeight: CGFloat = 0
        consumedHeight += appearance.kTitleTop + appearance.kTitleHeight
        consumedHeight += appearance.kVerticalSpacing
        consumedHeight += appearance.kTextFieldHeight * CGFloat(inputs.count)
        consumedHeight += appearance.kTextFieldHeight * CGFloat(inputWithLabels.count)
        tableHeight.forEach {
            consumedHeight += $0
        }
        consumedHeight += appearance.kButtonHeight * CGFloat(buttons.count)
        consumedHeight += appearance.kTextViewdHeight * CGFloat(input.count)
        if regionBtns.count > 0 {
            consumedHeight += appearance.kRegionBtnsHeight
        }
        
        let windowHeight = consumedHeight
        
        let x = (sz.width - appearance.kWindowWidth) / 2
        var y = (sz.height - windowHeight) / 3
        
        contentView.frame = CGRect(x: x, y: y, width: appearance.kWindowWidth, height: windowHeight)
        contentView.layer.cornerRadius = appearance.contentViewCornerRadius
        
        // Subtitle
        y = appearance.kTitleTop + appearance.kTitleHeight
        y += appearance.kVerticalSpacing
        
        // Text fields
        for txt in inputs {
            txt.frame = CGRect(x: appearance.kHorizontalSpacing, y: y, width: appearance.kWindowWidth - appearance.kHorizontalSpacing * 2, height: 30)
            txt.layer.cornerRadius = appearance.fieldCornerRadius
            y += appearance.kTextFieldHeight
        }
        
        // Label And Text fields
        for txt in inputWithLabels {
            txt.frame = CGRect(x: appearance.kHorizontalSpacing, y: y, width: appearance.kWindowWidth - appearance.kHorizontalSpacing * 2, height: 30)
            y += appearance.kTextFieldHeight
        }
        
        // textView
        for textView in input {
            textView.frame = CGRect(x: 3, y: y, width: appearance.kWindowWidth - 6, height: appearance.kTextViewdHeight - 10)
            y += appearance.kTextViewdHeight
        }
        // Table
        for i in 0..<tableS.count {
            tableS[i].frame = CGRect(x: 3, y: y, width: appearance.kWindowWidth - 6, height: tableHeight[i] - 10)
            tableS[i].layer.cornerRadius = appearance.fieldCornerRadius
            y += tableHeight[i]
        }
        
        
        for i in 0..<regionBtns.count {
            
            regionBtns[i].layer.cornerRadius = appearance.fieldCornerRadius
            let rw = appearance.reg_width
            let rp = appearance.reg_padding
            let temp_i = i % 4
            if i < 4 {
                regionBtns[i].frame = CGRect(x:12 + CGFloat(temp_i) * (rw + rp) ,y:y,width:rw,height: 35)
                print("1")
                print(regionBtns[i].frame)
            } else {
                regionBtns[i].frame = CGRect(x:12 + CGFloat(temp_i) * (rw + rp) ,y:y + 45,width:rw,height: 35)
                print("2")
                print(regionBtns[i].frame)
            }
            
        }
        if regionBtns.count > 0 {
            y += appearance.kRegionBtnsHeight
        }
        
        
        // Buttons
        for btn in buttons {
            btn.frame = CGRect(x: 3, y: y, width: appearance.kWindowWidth - 6, height: 35)
            btn.layer.cornerRadius = appearance.buttonCornerRadius
            y += appearance.kButtonHeight
        }
    }
    
    open override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        self.configUIlayout()
        
    }
    /// 单选控件，旧版待抛弃
    open func addPicker(_ title: String? = nil, singleConditionSelection data: [String], withLabel labelText: String, action: ((String) -> Void)?) -> KSETextField {
        
        let textfield = addTextField(title, withLabel: labelText)
        textfield.clearButtonMode = .never
        textfield.placeholder = "请选择 ▼"
        textfield.showSingleColPicker("", data: data, defaultSelectedIndex: 0, autoSetSelectedText: true) { (textField, _, selectedValue) in
            
            textField.text = selectedValue
            if let action = action {
                action(selectedValue)
            }
        }
        
        return textfield
    }
    /// 单选控件带搜索
    open func addPickerWithSearch(_ title: String? = nil, singleConditionSelection data: [String], withLabel labelText: String, action: ((String) -> Void)?) -> KSETextField {
        
        let textfield = addTextField(title, withLabel: labelText)
        textfield.clearButtonMode = .never
        textfield.placeholder = "请选择 ▼"
        textfield.delegate = self
        
        singlePickWithSearchArr.append(data)
        singlePickWithSearchClosure.append(action)
        textfield.tag = singlePickWithSearchArr.count + 1000
        
        return textfield
    }
 
    
    /// 月份筛选控件
    open func addPicker(title: String? = nil, withMonth labelText: String, action: ((String) -> Void)?) -> UITextField {
        
        dateTextField = addTextField(title, withLabel: labelText)
        dateTextField!.delegate = self
        dateTextField?.tag = 2
        return dateTextField!
    }
    
    open func addDatePicker(_ title: String? = nil, withLabel labelText: String, action: ((String) -> Void)?) -> KSETextField {
        
        let textfield = addTextField(title, withLabel: labelText)
        textfield.clearButtonMode = .never
        textfield.text = Date().toString
        textfield.showDatePicker("选择时间", autoSetSelectedText: true) { (textField, selectedDate) in
            let date = selectedDate.toString
            textField.text = date
            if let action = action {
                action(date)
            }
        }
        
        return textfield
    }
    
    open func addCalendar(_ title: String? = nil, withLabel labelText: String, subInfoDic:[String:String] = ["":""], action: ((String) -> Void)?) -> UITextField {
        
        self.subInfoDic = subInfoDic
        dateTextField = addTextField(title, withLabel: labelText)
        dateTextField!.delegate = self
        dateTextField?.tag = 1
        return dateTextField!
    }
    
    open func addTextField(_ title: String? = nil, withLabel labelText: String, action: ((String) -> Void)?) -> KSETextField {
        let txt = addTextField(title, withLabel: labelText)
        if let action = action {
            action(txt.text!)
        }
        return txt
    }
    // MARK: - 添加多选,单选控件   -------------------------------------------------------------------------
    open func addSelect(_ items:[SeString],title:String = "选择",mutiSelect:Bool = true) -> UICollectionView {
        
        mutiFlag.append(mutiSelect)
        let  itemHeight:CGFloat = 28
        let  headerHeight:CGFloat = 30
        var rowCount = (items.count + 1)/2 > 6 ? 6 : (items.count + 1)/2
        rowCount = rowCount == 0 ? 1 : rowCount
        let xxHeight = CGFloat(rowCount) * itemHeight + 20 + headerHeight
        
        tableHeight.append(xxHeight)
        appearance.setkWindowHeight(appearance.kWindowHeight + xxHeight)
        
        let layout = UICollectionViewFlowLayout()
        layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        layout.scrollDirection = .vertical
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.itemSize = CGSize(width: (appearance.kWindowWidth - 6)/2, height: itemHeight)
        layout.headerReferenceSize = CGSize.init(width: KSGlobal.screenW, height: headerHeight)
        
        
        let colleView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        colleView.register(KSColleCell.self, forCellWithReuseIdentifier: KSColleCell.identifier)
        colleView.register(CollectionHeader.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: CollectionHeader.identifier)
        colleView.backgroundColor = #colorLiteral(red: 0.9607843137, green: 0.9607843137, blue: 0.9607843137, alpha: 1)
        tableDataS.append(items)
        tableS.append(colleView)
        colleTitles.append(title)
        
        colleView.tag = tableS.count - 1
        colleView.delegate = self
        colleView.dataSource = self
        contentView.addSubview(colleView)
        
        
        return colleView
    }
    
    // MARK: - 添加区间选择时间空间   -------------------------------------------------------------------------
    open func addregionBtns() -> regionBtnProperty {
        appearance.setkWindowHeight(appearance.kWindowHeight + appearance.kRegionBtnsHeight)
        let txt0 = self.addCalendar(withLabel: "开始日期", action: nil)
        let txt1 = self.addCalendar(withLabel: "结束日期", action: nil)
        
        let titles = ["今天","昨天","本周","本月","最近3天","最近7天","上周","上月"]
        for i in 0..<titles.count {
            let btn:UIButton = UIButton()
            btn.backgroundColor = #colorLiteral(red: 0.9490196078, green: 0.9490196078, blue: 0.9490196078, alpha: 1)
            btn.setTitle(titles[i], for: .normal)
            btn.titleLabel!.font = UIFont.systemFont(ofSize: 15)
            btn.tag = i
            btn.addTarget(self, action: #selector(btnclick(sender:)), for: .touchUpInside)
            btn.setTitleColor(.darkGray, for: .normal)
            contentView.addSubview(btn)
            self.regionBtns.append(btn)
        }
        self.regionPro = regionBtnProperty(text0: txt0, text1: txt1,btns:self.regionBtns)
        return self.regionPro!
        
    }
    @objc func btnclick(sender:UIButton) {
        setSelect(sender.tag)
    }
    private func setSelect(_ index:Int) {
        if self.regionBtns.count > 0 {
            switch index {
            case 0:
                self.regionPro!.text0!.text = Date.today
                self.regionPro!.text1!.text = Date.today
            case 1:
                self.regionPro!.text0!.text = Date.todayPres(1)
                self.regionPro!.text1!.text = Date.todayPres(1)
            case 2:
                self.regionPro!.text0!.text = Date.getWeekTime(Date.today).0
                self.regionPro!.text1!.text = Date.getWeekTime(Date.today).1
            case 3:
                self.regionPro!.text0!.text = Date.firstDateOfMonth
                self.regionPro!.text1!.text = Date.endOfSomeMonth(Date.today)
            case 4:
                self.regionPro!.text0!.text = Date.todayPres(2)
                self.regionPro!.text1!.text = Date.today
            case 5:
                self.regionPro!.text0!.text = Date.todayPres(6)
                self.regionPro!.text1!.text = Date.today
            case 6:
                self.regionPro!.text0!.text = Date.getWeekTime(Date.todayPres(7)).0
                self.regionPro!.text1!.text = Date.getWeekTime(Date.todayPres(7)).1
            case 7:
                self.regionPro!.text0!.text = Date.preMonths_1(1)
                self.regionPro!.text1!.text = Date.endOfSomeMonth(Date.preMonths_1(1))
            default:
                break
            }
            
            
            
            for i in 0..<self.regionBtns.count {
                if index == i {
                    self.regionBtns[i].backgroundColor = #colorLiteral(red: 0.07058823529, green: 0.5882352941, blue: 0.8588235294, alpha: 1)
                    self.regionBtns[i].setTitleColor(.white, for: .normal)
                } else {
                    self.regionBtns[i].backgroundColor = #colorLiteral(red: 0.9490196078, green: 0.9490196078, blue: 0.9490196078, alpha: 1)
                    self.regionBtns[i].setTitleColor(.darkGray, for: .normal)
                }
            }
            
        }
    }
    
    
    open func addTextView() -> UITextView {
        appearance.setkWindowHeight(appearance.kWindowHeight + appearance.kTextViewdHeight)
        
        let textView = UITextView()
        textView.font = UIFont.systemFont(ofSize: 14)
        textView.layer.cornerRadius = 5
        textView.layer.borderColor = UIColor.lightGray.cgColor
        textView.layer.borderWidth = 1
        contentView.addSubview(textView)
        input.append(textView)
        return textView
    }
    
    open func addTextField(_ title: String? = nil, withLabel labelText: String) -> KSETextField {
        
        let view:UIView = UIView()
        let textfield = addTextField(title, whetherToAdd: false)
        
        let label :UILabel = UILabel()
        label.text = labelText + ":"
        label.textColor = appearance.labelColor
        label.font = appearance.kLalelFont
        label.frame = CGRect(x: 0, y: 0, width: appearance.kLabelWidth, height: 30)
        
        view.addSubview(textfield)
        view.addSubview(label)
        
        contentView.addSubview(view)
        inputWithLabels.append(view)
        return textfield
    }
    
    open func addCustomTextField(_ title: String? = nil, withLabel labelText: String) -> UITextField {
        
        let view:UIView = UIView()
        let textfield: UITextField = UITextField()
        textfield.frame = CGRect(x: appearance.kLabelWidth, y: 0, width: appearance.kWindowWidth - appearance.kHorizontalSpacing * 2 - appearance.kLabelWidth, height: 30)
        
        textfield.placeholder = title
        textfield.borderStyle = UITextField.BorderStyle.roundedRect
        textfield.font = appearance.kTextFont
        textfield.textAlignment = .center
        textfield.autocapitalizationType = .words
        textfield.clearButtonMode = UITextField.ViewMode.whileEditing
        textfield.layer.masksToBounds = true
        
        if let placeholder = title {
            textfield.placeholder = placeholder
        }
        
        let label :UILabel = UILabel()
        label.text = labelText + ":"
        label.textAlignment = .right
        label.textColor = appearance.labelColor
        label.font = appearance.kLalelFont
        label.frame = CGRect(x: 0, y: 0, width: appearance.kLabelWidth, height: 30)
        
        view.addSubview(textfield)
        view.addSubview(label)
        
        contentView.addSubview(view)
        inputWithLabels.append(view)
        return textfield
    }
    
    open func addRemindLabel(_ title: String? = nil, withLabel labelText: String) -> UILabel {
        
        var height: CGFloat = 0.01
        if title == nil {
            height = appearance.kWindowWidth - appearance.kHorizontalSpacing * 2 - appearance.kLabelWidth
        }
        let view:UIView = UIView()
        let textfield: UITextField = UITextField()
        if title == nil {
            height = appearance.kWindowWidth - appearance.kHorizontalSpacing * 2 - appearance.kLabelWidth
            textfield.isHidden = true
        }
        textfield.frame = CGRect(x: appearance.kLabelWidth, y: 0, width: height, height: 30)
        
        textfield.placeholder = title
        textfield.borderStyle = UITextField.BorderStyle.roundedRect
        textfield.font = appearance.kTextFont
        textfield.textAlignment = .center
        textfield.autocapitalizationType = .words
        textfield.clearButtonMode = UITextField.ViewMode.whileEditing
        textfield.layer.masksToBounds = true
        
        if let placeholder = title {
            textfield.placeholder = placeholder
        }
        
        if title != nil {
            height = appearance.kWindowWidth - appearance.kHorizontalSpacing * 2 - appearance.kLabelWidth
        }
        
        let label :UILabel = UILabel()
        label.text = labelText
        label.textAlignment = .left
        label.textColor = appearance.labelColor
        label.font = appearance.kLalelFont
        label.frame = CGRect(x: -15.0, y: 0, width: appearance.kLabelWidth + height + 30, height: 30)
        
        view.frame.size.width += 30
        
        view.addSubview(textfield)
        view.addSubview(label)
        
        contentView.addSubview(view)
        inputWithLabels.append(view)
        return label
    }
    
    open func addTextField(_ title: String? = nil) -> UITextField {
        return addTextField(title, whetherToAdd: true)
    }
    
    fileprivate func addTextField(_ title: String? = nil, whetherToAdd: Bool) -> KSETextField {
        appearance.setkWindowHeight(appearance.kWindowHeight + appearance.kTextFieldHeight)
        
        let txt = KSETextField()
        txt.borderStyle = UITextField.BorderStyle.roundedRect
        txt.font = appearance.kTextFont
        txt.textAlignment = .center
        txt.autocapitalizationType = .words
        txt.clearButtonMode = UITextField.ViewMode.whileEditing
        txt.layer.masksToBounds = true
        
        if let placeholder = title {
            txt.placeholder = placeholder
        }
        
        if whetherToAdd {
            contentView.addSubview(txt)
            inputs.append(txt)
        } else {
            txt.frame = CGRect(x: appearance.kLabelWidth, y: 0, width: appearance.kWindowWidth - appearance.kHorizontalSpacing * 2 - appearance.kLabelWidth, height: 30)
        }
        
        return txt
    }
    
    open func addButton(_ title: String, backgroundColor: UIColor? = nil, textColor: UIColor? = nil, action: @escaping () -> Void) -> KSButton {
        let btn = addButton(title, backgroundColor: backgroundColor, textColor: textColor)
        btn.actionType = KSActionType.closure
        btn.action = action
        btn.addTarget(self, action: #selector(KSAlertView.buttonTapped(_:)), for: .touchUpInside)
        return btn
    }
    
    open func addButton(_ title: String, backgroundColor: UIColor? = nil, textColor: UIColor? = nil, showDurationStatus: Bool = false, target: AnyObject, selector: Selector) -> KSButton {
        let btn = addButton(title, backgroundColor: backgroundColor, textColor: textColor)
        btn.actionType = KSActionType.closure
        btn.target = target
        btn.selector = selector
        btn.addTarget(self, action: #selector(KSAlertView.buttonTapped(_:)), for: .touchUpInside)
        return btn
    }
    
    open func addButton(_ title: String, backgroundColor: UIColor? = nil, textColor: UIColor? = nil) -> KSButton {
        appearance.setkWindowHeight(appearance.kWindowHeight + appearance.kButtonHeight)
        
        let btn = KSButton()
        btn.layer.masksToBounds = true
        btn.backgroundColor = Theme.primaryColor()
        btn.setTitle(title, for: UIControl.State())
        btn.titleLabel?.font = appearance.kButtonFont
        contentView.addSubview(btn)
        buttons.append(btn)
        return btn
    }
    
    @objc func buttonTapped(_ btn: KSButton) {
        
        if btn.actionType == KSActionType.closure {
            btn.action()
        } else if btn.actionType == KSActionType.selector {
            let ctrl = UIControl()
            ctrl.sendAction(btn.selector, to: btn.target, for: nil)
        } else {
            print("Unknow action type for button")
        }
        
        if view.alpha != 0.0 && appearance.shouldAutoDismiss { hideView() }
    }
    
    //Dismiss keyboard when tapped outside textfield & close AlertView when hideWhenBackgroundViewIsTapped
    @objc func tapped(_ gestureRecognizer: UITapGestureRecognizer) {
        self.view.endEditing(true)
        
        if let tappedView = gestureRecognizer.view, tappedView.hitTest(gestureRecognizer.location(in: tappedView), with: nil) == baseView
            && appearance.hideWhenBackgroundViewIsTapped {
            
            hideView()
        }
    }
    
    open func show(_ title: String, duration: TimeInterval?, completeText: String?, colorStyle: UInt? = 0x000000, colorTextButton: UInt? = 0xFFFFFF, animationStyle: KSAnimationStyle = .bottomToTop) {
        selfReference = self
        view.alpha = 0
        let rv = getKeyWindow()!
        rv.addSubview(view)
        view.frame = rv.bounds
        baseView.frame = rv.bounds
        
        self.resignFirstResponder()
        
        if !title.isEmpty {
            self.labelTitle.text = title
        }
        
        showAnimation(animationStyle)
    }
 
    // Show animation in the alert view
    fileprivate func showAnimation(_ animationStyle: KSAnimationStyle = .topToBottom, animationStartOffset: CGFloat = -400.0, boundingAnimationOffset: CGFloat = 15.0, animationDuration: TimeInterval = 0.2) {
        
        let rv = getKeyWindow()!
        var animationStartOrigin = baseView.frame.origin
        var animationCenter = rv.center
        
        switch animationStyle {
        case .noAnimation:
            view.alpha = 1.0
            return
            
        case .topToBottom:
            animationStartOrigin = CGPoint(x: animationStartOrigin.x, y: baseView.frame.origin.y + animationStartOffset)
            animationCenter = CGPoint(x: animationCenter.x, y: animationCenter.y + boundingAnimationOffset)
            
        case .bottomToTop:
            animationStartOrigin = CGPoint(x: animationStartOrigin.x, y: baseView.frame.origin.y - animationStartOffset)
            animationCenter = CGPoint(x: animationCenter.x, y: animationCenter.y - boundingAnimationOffset)
            
        case .leftToRight:
            animationStartOrigin = CGPoint(x: baseView.frame.origin.x + animationStartOffset, y: animationStartOrigin.y)
            animationCenter = CGPoint(x: animationCenter.x + boundingAnimationOffset, y: animationCenter.y)
            
        case .rightToLeft:
            animationStartOrigin = CGPoint(x: baseView.frame.origin.x - animationStartOffset, y: animationStartOrigin.y)
            animationCenter = CGPoint(x: animationCenter.x - boundingAnimationOffset, y: animationCenter.y)
        }
        
        baseView.frame.origin = animationStartOrigin
        UIView.animate(withDuration: animationDuration, animations: {
            self.view.alpha = 1.0
            self.baseView.center = animationCenter
        }, completion: { _ in
            UIView.animate(withDuration: animationDuration, animations: {
                self.view.alpha = 1.0
                self.baseView.center = rv.center
            })
        })
    }
    
    
    open func showFromBottom(_ title: String, duration: TimeInterval?, completeText: String?, colorStyle: UInt? = 0x000000, colorTextButton: UInt? = 0xFFFFFF) {
        selfReference = self
        view.alpha = 0
        let rv = UIApplication.shared.keyWindow! as UIWindow
        rv.addSubview(view)
        view.frame = rv.bounds
        baseView.frame = rv.bounds
        
        self.resignFirstResponder()
        
        if !title.isEmpty {
            self.labelTitle.text = title
        }
        
        showAnimationFromBottom()
    }
    // Show animation in the alert view
    fileprivate func showAnimationFromBottom(animationStartOffset: CGFloat = -400.0, boundingAnimationOffset: CGFloat = 15.0, animationDuration: TimeInterval = 0.2) {
        
        let rv = UIApplication.shared.keyWindow! as UIWindow
        var animationStartOrigin = baseView.frame.origin
        
        

        animationStartOrigin = CGPoint(x: animationStartOrigin.x, y: baseView.frame.origin.y - animationStartOffset)
 
        baseView.frame.origin = animationStartOrigin
        
        let piancha = KSGlobal.screenH - appearance.kWindowHeight
        
        

        var finalCenter = CGPoint(x: rv.center.x, y: rv.center.y + piancha)
        var animationCenter = CGPoint(x: finalCenter.x, y: finalCenter.y - 15)

         
        UIView.animate(withDuration: animationDuration, animations: {
            self.view.alpha = 1.0
            self.baseView.center = animationCenter
        }, completion: { _ in
            UIView.animate(withDuration: animationDuration, animations: {
                self.view.alpha = 1.0
                self.baseView.center = finalCenter
            })
        })
    }
    
    
    @objc open func hideView() {
        UIView.animate(withDuration: 0.2, animations: {
            self.view.alpha = 0
        }, completion: { _ in
            
            for button in self.buttons {
                button.action = nil
                button.target = nil
                button.selector = nil
            }
            
            self.view.removeFromSuperview()
            self.selfReference = nil
        })
    }
    
    // × 图
    var imageOfCross: UIImage {
        UIGraphicsBeginImageContextWithOptions(CGSize(width: 20, height: 20), false, 0)
        drawCross()
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image!
    }
    
    // 画 ×
    func drawCross() {
        // Cross Shape Drawing
        let crossShapePath = UIBezierPath()
        crossShapePath.move(to: CGPoint(x: 0, y: 20))
        crossShapePath.addLine(to: CGPoint(x: 20, y: 0))
        crossShapePath.move(to: CGPoint(x: 0, y: 0))
        crossShapePath.addLine(to: CGPoint(x: 20, y: 20))
        crossShapePath.lineCapStyle = CGLineCap.square
        crossShapePath.lineJoinStyle = CGLineJoin.round
        UIColorFromRGB(0x4D4D4D).setStroke()
        crossShapePath.lineWidth = 1
        crossShapePath.stroke()
    }
    
    override open var shouldAutorotate: Bool {
        return true
    }
    
    override open var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return UIInterfaceOrientationMask.portrait
    }
    
    override open var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
        return UIInterfaceOrientation.portrait
    }
}

extension KSAlertView:UICollectionViewDelegate,UICollectionViewDataSource {
    
    public func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        var reusableView :CollectionHeader?
        if  kind == UICollectionView.elementKindSectionHeader {
            
            reusableView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: CollectionHeader.identifier, for: indexPath) as! CollectionHeader
            reusableView?.lab.text = colleTitles[collectionView.tag]
        }
        return reusableView!
    }
    
    public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return tableDataS[collectionView.tag].count
    }
    
    public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: KSColleCell.identifier, for: indexPath) as! KSColleCell
        cell.btn.setTitle(tableDataS[collectionView.tag][indexPath.row].title, for: .normal)
        cell.btn.isSelected = tableDataS[collectionView.tag][indexPath.row].ks_selected
        cell.atSession = collectionView.tag
        cell.atRow = indexPath.row
        cell.btnAction = { session,row in
            
            if self.mutiFlag[session] {  // 多选事件
                
                self.tableDataS[session][row].ks_selected = !self.tableDataS[session][row].ks_selected
                
                // 如果选切换了第一个（全部），那么下面所有的都和第一个一样
                if row == 0 {
                    for i in 1..<self.tableDataS[session].count {
                        self.tableDataS[session][i].ks_selected = self.tableDataS[session][0].ks_selected
                    }
                }
                // 如果有人没选中，那么第一个不能选中，如果全部都选中，第一个必须选中
                var xtemp = true
                for i in 1..<self.tableDataS[session].count {
                    if self.tableDataS[session][i].ks_selected == false {
                        xtemp = false
                    }
                }
                self.tableDataS[session][0].ks_selected = xtemp
                
                self.tableS[session].reloadData()
            } else {  // 单选事件
                self.tableDataS[session][row].ks_selected = true
                
                for i in 0..<self.tableDataS[session].count {
                    if i != row {
                        self.tableDataS[session][i].ks_selected = false
                    }
                }
                self.tableS[session].reloadData()
            }
            
            
            
        }
        
        return cell
    }
    
    
}

// Helper function to convert from RGB to UIColor
func UIColorFromRGB(_ rgbValue: UInt) -> UIColor {
    return UIColor(
        red:   CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
        green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
        blue:  CGFloat(rgbValue & 0x0000FF) / 255.0,
        alpha: CGFloat(1.0)
    )
}

extension KSAlertView: UITextFieldDelegate {
    
    public func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        dateTextField = textField
        
        if textField.tag == 2 { //  月份筛选
            let view = KSSelectMonthView()
            view.fetchData = { month in
                self.dateTextField!.text = month
            }
            view.show()
        } else if textField.tag > 1000 && textField.tag <= singlePickWithSearchArr.count + 1000 {
            
            var allArr = [nameAndModel<String>]()
            for item in singlePickWithSearchArr[textField.tag - 1000 - 1] {
                let one_x = nameAndModel(shows: [item], model: item)
                allArr.append(one_x)
            }
            
            let cle:(nameAndModel<String>)->() = { one in
                textField.text = one.model
                if let clo = self.singlePickWithSearchClosure[textField.tag - 1000 - 1] {
                    clo(one.model)
                }
            }
            
            let vc = KSSingleSelectUtil.initWithNav(title: "选择", allArr: allArr, backClosure: cle)
            self.present_FullScreen(to: vc)
            
            
            
        } else if textField.tag == 1 { // 日历筛选
            
            let cvc = KSCalendar()
            cvc.subInfoDic = self.subInfoDic
            cvc.delegate = self
            cvc.isRadio = true
            
            let nav = BaseNavigationController()
            nav.viewControllers = [cvc]
            self.present_FullScreen(to: nav)
           
        }
        
        return false
    }
}

extension KSAlertView: KSCalendarDelegate {
    
    func calendarViewSelectDate(_ date: String?) {
        if let tempDate = date {
            dateTextField?.text = tempDate
        }
    }
}

extension Date {
    var toString: String {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        return formatter.string(from: self)
    }
}

class CollectionHeader:UICollectionReusableView {
    
    var lab:UILabel!
    override init(frame: CGRect) {
        super.init(frame: frame)
        lab = UILabel(frame: self.bounds)
        lab.font = UIFont.systemFont(ofSize: 14)
        lab.textColor = #colorLiteral(red: 0.2549019754, green: 0.2745098174, blue: 0.3019607961, alpha: 1)
        addSubview(lab)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
